package com.atguigu.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ：MJS
 * @date ：Created in 2021/4/25  14:54
 * @description：TODO
 */
public class ProConsumerOfCondition {
    public static void main(String[] args) {
        AirCondition airCondition = new AirCondition();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(200);
                    airCondition.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"张三").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(300);
                    airCondition.sub();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"李四").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(400);
                    airCondition.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"王五").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(500);
                    airCondition.sub();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"赵六").start();
    }
}

class AirCondition{//资源类
    private int number=0;
    private Lock lock=new ReentrantLock();
    private Condition condition=lock.newCondition();
    public  void add() throws InterruptedException {

        lock.lock();
                try
                {
                    //1.判断
                    while (number !=0){
                        condition.await();
                    }
                    //2.干活
                    number++;
                    System.out.println(Thread.currentThread().getName()+"\t"+number);
                    //3.通知
                    condition.signal();
                }finally {
                    lock.unlock();
                }


    }

    public  void sub() throws InterruptedException {

        lock.lock();
        try
        {
            //1.判断
            while (number ==0){
                condition.await();
            }
            //2.干活
            number--;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            //3.通知
            condition.signal();
        }finally {
            lock.unlock();
        }

    }

}
